package com.zjc.springboot.nettyclient.handler;

import com.zjc.springboot.nettyclient.client.NettyClient;
import com.zjc.springboot.nettyclient.v15.Protocol15;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

@ChannelHandler.Sharable
public class Msg15Handler extends ChannelInboundHandlerAdapter {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private NettyClient nettyClient;

    public Msg15Handler(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }


    @Override
    public void channelRead(ChannelHandlerContext channelHandlerContext, Object msg) throws Exception {
        String receive = (String) msg;
        handlReceive(receive);
        log.info("收到消息执行：" + msg);
    }

    public void handlReceive(String receive) {
        System.out.println(new Date() + "  client receive：  " + receive);
        int cmdId = Integer.parseInt(receive.substring(4, 6), 16);
        String ser = receive.substring(6, 14);
        String ter = receive.substring(14, 27);
        int dataLen = Integer.parseInt(receive.substring(30, 34), 16);
        String data = receive.substring(34, (receive.length() - 4));

        if (cmdId == 0x12) {
            String key = data.substring(0, 2);
            String opt = data.substring(2, 4);
            if (opt.equals("01")) {
                String value = data.substring(4, 6);
                nettyClient.setParam(key, value);
                nettyClient.sendMessage(Protocol15.paramSetResponse(ter, ser));
            }
            if (opt.equals("00")) {
                String value = nettyClient.getParam(key);
                nettyClient.sendMessage(Protocol15.paramQueryResponse(ter, ser));
            }
        }
        if (cmdId == 0x11) {
            nettyClient.sendMessage(Protocol15.locateQueryResponse(ter, ser, nettyClient.getConfig().getLon(), nettyClient.getConfig().getLon()));
        }
        if (cmdId == 0x13) {
            nettyClient.sendMessage(Protocol15.limitSpeedResponse(ter, ser));
        }
    }
}
